package com.example.baron;

import android.app.Fragment;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TimerFragment extends Fragment implements View.OnClickListener {
	static View v;
	boolean isRun = false;
	long startTime = 0;
	Handler tickHandler = new Handler();
	TextView clockTV;

	int seconds;
	int minutes;
	int hours;
	int milliseconds;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
			Bundle savedInstanceState) {

		try {
			v = inflater.inflate(R.layout.fragment, viewGroup, false);
		} catch (InflateException e) {
		}

		LinearLayout rootView = (LinearLayout) inflater.inflate(
				R.layout.fragment, viewGroup, false);
		rootView.setOnClickListener(this);
		clockTV = (TextView) rootView.findViewById(R.id.clockTV);

		return rootView;
	}

	@Override
	public void onClick(View view) {
		toggle();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if (v != null) {
			ViewGroup parent = (ViewGroup) v.getParent();
			if (parent != null) {
				parent.removeView(v);
			}
		}

	}

	void toggle() {
		isRun = !isRun;
		if (isRun) {
			startTime = SystemClock.uptimeMillis();
			tickHandler.postDelayed(tickThread, 0);
			toast("START");

			BackThread thread = new BackThread();
			thread.setDaemon(true);
			thread.start();

		} else {
			tickHandler.removeCallbacks(tickThread);
		}
	}

	void toast(String message) {
		Toast.makeText(getView().getContext(), message, Toast.LENGTH_SHORT)
				.show();
	}

	Runnable tickThread = new Runnable() {

		@Override
		public void run() {
			long diff = SystemClock.uptimeMillis() - startTime;
			seconds = (int) (diff / 1000);

			minutes = (seconds / 60);
			seconds %= 60;

			hours = (minutes / 60);
			minutes %= 60;

			milliseconds = (int) (diff % 1000);
			clockTV.setText(String.format("%02d:%02d:%02d.%03d", hours,
					minutes, seconds, milliseconds));
			tickHandler.postDelayed(tickThread, 0);
		}
	};

	class BackThread extends Thread {

		public void run() {
			while (true) {
				mHandler.sendEmptyMessage(0);

				try {
					Thread.sleep(10000);

				} catch (InterruptedException e) {

					e.printStackTrace();
				}
			}
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				
				clockTV.setText("바론 출현");
				mHandler.sendEmptyMessage(1);
			}
			if(msg.what == 1) {
				tickHandler.removeCallbacks(tickThread);
			}

		}
	};
}
